package com.yisin.commun.server;

import java.util.UUID;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSONObject;
import com.yinsin.other.LogHelper;
import com.yisin.commun.modal.Client;
import com.yisin.commun.modal.Data;
import com.yisin.commun.modal.DataCache;
import com.yisin.commun.modal.DataPackage;
import com.yisin.commun.modal.HandlerMethod;
import com.yisin.commun.util.JSONUtils;

@ServerEndpoint(value = "/ws")
public class YSWebSocketPoint {
    private static final LogHelper logger = LogHelper.getLogger(YSWebSocketPoint.class);
    
    private static IMessageHandler handle;

    public static IMessageHandler getHandle() {
        return handle;
    }

    public static void setHandle(IMessageHandler h) {
        handle = h;
    }

    @OnOpen
    public void open(Session session, EndpointConfig config) {
        Client ws = new Client(session);
        ws.setSid(session.getId());
        ws.setQueryString(session.getQueryString() == null ? "" : session.getQueryString());
        ws.setConfig(config);
        String uuid = UUID.randomUUID().toString();
        ws.setUuid(uuid.replaceAll("-", ""));
        handle.onOpen(ws);
    }

    @OnMessage
    public void inMessage(Session session, String message) {
        try {
            Client client = DataCache.getBySid(session.getId());
            if (null != client) {
            	System.out.println("message===>" + message);
            	JSONObject json = JSONObject.parseObject(message);
            	Data msgData = JSONUtils.toJavaObject(json, Data.class);
            	msgData.setValue(json.get("value"));
                
                DataPackage pack = new DataPackage(msgData);
                
                if(handle.filter(client, pack)){
                	callOnMessage(client, pack);
                }
            }
        } catch (Exception e) {
            logger.error("接收消息异常：" + session.getId(), e);
        }
    }

    @OnClose
    public void end(Session session) {
        try {
            Client client = DataCache.getBySid(session.getId());
            if (null != client) {
                client.setStatus(1001);
                handle.onClose(client);
                DataCache.removeBySid(session.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void error(Session session, Throwable throwable) {
        try {
            Client client = DataCache.getBySid(session.getId());
            if (null != client) {
                client.setStatus(1003);
                handle.onError(client, throwable);
                DataCache.removeBySid(session.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void callOnMessage(Client client, DataPackage pack){
    	String url = pack.getReq();
    	if(url != null){
    		url = url.replaceAll("/", ".");
    	}
    	HandlerMethod handMethod = HandleHelper.getHandlerMethod(url);
    	if(null != handMethod){
    		try {
				handMethod.getMethod().invoke(handMethod.getInstance(), new Object[]{
					client, pack				
				});
			} catch (Exception e) {
				handle.onMessage(client, pack);
			}
    	} else {
    		handle.onMessage(client, pack);
    	}
    }
    
    private class _YSWebSocketPoint {
        
    }

}
